# 根据数据采集器的数据，使用报告模版生成测试报告
from three_robot.robot.services.tools import pro_path
from configparser import ConfigParser


class Repoter:
    skip = 0  # 跳过用例数
    passed = 0  # 通过用例数
    fail = 0  # 失败用例数
    all = 0  # 总用例总数
    exec = 0  # 执行的用例数
    erro = 0  # 错误用例数

    rst = []  # 用例执行结果

    def __init__(self, repoterpath):
        self.cfg = ConfigParser()
        self.cfg.read(pro_path('three_robot') + '/conf.ini', encoding="utf-8")
        self.repoter_name = self.cfg.get('ci', 'repoter_headname')
        self.repoterpath = repoterpath
        self.template = pro_path('three_robot') + '/robot/view/static/template.html'

    def generate_repoter(self, data):

        # try:
        if data:
            for i in range(len(data)):
                self.all += 1
            self.exec = self.all - self.skip  # 执行的用例数

            with open(self.template, 'r', encoding='utf8') as f:
                content = f.read()
                content = content.replace('!title', self.repoter_name + '_自动化测试报告')
                content = content.replace('!all', str(self.all))
                content = content.replace('!skip', str(self.skip))

                content = content.replace('!exec', str(self.exec))
                content = content.replace('!pass', str(self.passed))
                content = content.replace('!fail', str(self.fail))
                content = content.replace('!erro', str(self.erro))
                xinxi_lis = '<table border="1" cellspacing="0" bgcolor="green" cellpadding="7">'
                xinxi_lis += '<thead><tr><th>模块</th><th>标题</th><th>测试数据</th><th>标记位</th><th>结果</th></tr>' \
                             '</thead>'
                i = 0
                # print(Repoter.rst)
                # print(data, self.rst)
                for tc in data:
                    xinxi_lis += '<tbody><tr> ' \
                                 f'<td><font>{tc.module}</font></td><td>{tc.describe}</td><td>{tc.steps}</td><td>{tc.flag}</td><td>{self.rst[i]}</td>' \
                                 '</tr></tbody>'
                    i += 1
                xinxi_lis += '</table>'

                content = content.replace('$content', xinxi_lis)
            with open(self.repoterpath, 'w', encoding='utf8') as f:
                f.write(content)
            Repoter.fail, Repoter.exec, Repoter.all, Repoter.skip, Repoter.erro, Repoter.passed = 0, 0, 0, 0, 0, 0
            Repoter.rst = []

            # print(Repoter.fail,Repoter.exec,Repoter.all,Repoter.skip,Repoter.erro,Repoter.passed)
            # print(Repoter.rst)
        else:
            print('数据为空！')
    # except Exception as e:
    #     print(e)

# if __name__ == '__main__':
#
#     a=Repoter('./repoter.html')
#     a.generate_repoter(1)
